﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Tools.Data;
using Tools.Models;
using Tools.Service;
using Tools.Utils;
using Tools.Web.Models;

namespace Tools.Controllers
{
    public class PDFController : Controller
    {
        private readonly ILogger<PDFController> _logger;

        public PDFController(ILogger<PDFController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// PDF转图片
        /// </summary>
        /// <returns></returns>
        public IActionResult PDFToImage()
        {
            return View();
        }

        /// <summary>
        /// pdf转图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePDFToImage(string oldPath)
        {
            ResultMessage resultMessage = new ResultMessage();

            var formCollection = Request.Form;
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();

            if (filelist.Count() == 0 && string.IsNullOrWhiteSpace(oldPath))
            {
                return Json(resultMessage.Failure("请上传文件"));
            }

            var showUrl = "";

            try
            {
                string oldName = Path.GetFileName($"{ FileHelper.UploadFilePath}/{oldPath}");
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\pdf\\{newFileName}";
                showUrl = $"/files/pdf/{newFileName}";

                DirectoryInfo di = new DirectoryInfo(saveFilePath);
                if (!di.Exists) { di.Create(); }

                var imageTotal = new PdfService().PdfToImages($"{FileHelper.UploadFilePath}\\{oldPath}", saveFilePath);

                return Json(resultMessage.Success(new { msg = $"转换成功，共{imageTotal}张。", url = $"{showUrl}.zip" }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// PDF加水印
        /// </summary>
        /// <returns></returns>
        public IActionResult PDFAddWatermark()
        {
            return View();
        }

        /// <summary>
        /// pdf添加水印
        /// </summary>
        /// <param name="oldPath">pdf路径</param>
        /// <param name="watermarkPath">水印图片路径</param>
        /// <param name="waterMarkName">水印文字</param>
        /// <param name="type">类型（img-图片,text-文字）</param>
        /// <param name="number">水印数量（one-一个，covered-铺满）</param>
        /// <param name="location">水印位置(top-内容上面，bottom-内容下面)</param>
        /// <param name="rotation">旋转角度</param>
        /// <param name="layout">布局（1-左上方，2顶部中间，3-右上方，4-左边，5-中间，6-右边，7-左下方，8-底部中间，9-右下方）</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePDFAddWatermark(string oldPath,string watermarkPath, string waterMarkName, string type,string number,string location,string rotation,string layout)
        {
            ResultMessage resultMessage = new ResultMessage();

            var formCollection = Request.Form;
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();

            if (filelist.Count() == 0 && string.IsNullOrWhiteSpace(oldPath))
            {
                return Json(resultMessage.Failure("请上传文件"));
            }

            var showUrl = "";

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\pdf\\{newFileName}.pdf";
                showUrl = $"/files/pdf/{newFileName}.pdf";

                var imageTotal = new PdfService().PdfWaterMark(saveFilePath,$"{FileHelper.UploadFilePath}\\{oldPath}",$"{FileHelper.UploadFilePath}\\{watermarkPath}", waterMarkName, type, number,location,rotation,layout);

                return Json(resultMessage.Success(new { msg = $"水印添加成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// PDF合并
        /// </summary>
        /// <returns></returns>
        public IActionResult PDFMerge()
        {
            return View();
        }

        /// <summary>
        /// pdf合并
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePDFMerge(List<string> oldPath)
        {
            ResultMessage resultMessage = new ResultMessage();

            var formCollection = Request.Form;
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();

            if (filelist.Count() == 0 && (oldPath==null||!oldPath.Any()))
            {
                return Json(resultMessage.Failure("请上传文件"));
            }

            var showUrl = "";

            try
            {
                var fileList = oldPath;
                fileList= fileList.Select(t=> $"{FileHelper.UploadFilePath}\\{t}").ToList();

                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\pdf\\{newFileName}.pdf";
                showUrl = $"/files/pdf/{newFileName}.pdf";

                new PdfService().MergePDFFiles(fileList, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"已将{fileList.Count}个文件合并为一个。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

    }
}
